// src/axios.ts
import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import sysConfig from "../config";
import { ElMessage } from "element-plus";
import routerInstance from '@/router/index'

// 创建一个axios实例
const instance: AxiosInstance = axios.create({
  //   baseURL: 'https://api.example.com', // 设置你的API基础路径
  baseURL: "/api", // api base_url
  timeout: 60000, // 设置请求超时时间
  // headers: { "Content-Type": "application/json" },
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers[sysConfig.TOKEN_NAME] = sysConfig.TOKEN_PREFIX + token;
    }
    if (!sysConfig.REQUEST_CACHE && config.method === "get") {
      config.params = config.params || {};
      config.params._ = new Date().getTime();
    }
    Object.assign(config.headers, sysConfig.HEADERS);
    return config;
  },
  (error: any): Promise<any> => {
    // 处理请求错误
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse): Promise<any> => {
    // 配置了blob，不处理直接返回文件流
    if (response.config.responseType === "blob") {
      if (response.status === 200) {
        return Promise.resolve(response);
      } else {
        // message.warning("文件下载失败或此文件不存在");
        return Promise.reject();
      }
    }

    const data: any = response.data;
    const code: number = data.code;

    // if (reloadCodes.includes(code)) {
    //  if (!loginBack.value) {
    //    error()
    //  }
    //  return
    // }
    if (code === 401) {
      ElMessage({
        message: "登录已过期，请重新登录",
        type: "error",
        plain: true,
      });
      // 刷新页面
      localStorage.removeItem("token");
      routerInstance.push('/login')
      // location.reload();
    }

    if (code !== 200 && code !== 401) {
      // const customErrorMessage = response.config.customErrorMessage
      // message.error(customErrorMessage || data.msg)
      ElMessage({
        message: data.msg,
        type: "error",
        plain: true,
      });
      return Promise.reject(data);
    } else {
      // 统一成功提示
      const responseUrls: string[] = (response.config.url || "").split("/");
      const apiNameArray: string[] = [
        "add",
        "edit",
        "delete",
        "update",
        "grant",
        "reset",
        "stop",
        "pass",
        "disable",
        "enable",
        "revoke",
        "suspend",
        "active",
        "turn",
        "adjust",
        "reject",
        "saveDraft",
      ];
      // apiNameArray.forEach((apiName) => {
      //  if (responseUrls[responseUrls.length - 1].includes(apiName)) {
      //    message.success(data.msg)
      //  }
      // })
    }
    return Promise.resolve(data.data);
  },
  (error: any): Promise<number> => {
    if (error) {
      const status: number = 503;
      console.log(error);

      // const description = errorCodeMap[status]
      // notification.error({
      //  message: '请求错误',
      //  description
      // })
      if (error.code !== 401) {
        ElMessage({
          message: error.msg,
          type: "error",
          plain: true,
        });
      }
      return Promise.reject(status);
    }
    return Promise.reject(error);
  }
);

// 适配器, 用于适配不同的请求方式
interface RequestOptions extends AxiosRequestConfig {
  customErrorMessage?: string;
}

export const baseRequest = (
  url: string,
  value: any = {},
  method: string = "post",
  options: RequestOptions = {}
): Promise<any> => {
  url = sysConfig.API_URL + url;
  if (method === "post") {
    return instance.post(url, value, options);
  } else if (method === "get") {
    return instance.get(url, { params: value, ...options });
  } else if (method === "formdata") {
    // form-data表单提交的方式
    return instance.post(url, JSON.stringify(value), {
      headers: {
        "Content-Type": "multipart/form-data",
      },
      ...options,
    });
  } else {
    // 其他请求方式，例如：put、delete
    return instance({
      method: method,
      url: url,
      data: value,
      ...options,
    });
  }
};

// 模块内的请求, 会自动加上模块的前缀
export const moduleRequest =
  (moduleUrl: string) =>
  (url: string, ...arg: any[]): Promise<any> => {
    return baseRequest(moduleUrl + url, ...arg);
  };

export default instance;
